import Config from '../../common/app/config.js';
import constants from '../../common/app/constant.js';
import Tools from '../../common/app/tools.js';
import StorageNative from '../../common/app/storageNative.js';
import SoundNative from '../../common/app/soundNative.js';

export default {
    props: [],
    data: {
        MIN_DIS: 64,
        setX: 0, //起始点XY坐标
        setY: 0,
        offsetX: 0,
        offsetY: 0,
        cells: null, //二维数组，用来显示数据
        dataAfterSwipe: [],
        emptyCellPoint: [],
        recordPreviousDigital: -1, //滑动后记录上一个位置的数字
        someData: [], //记录滑动前的一行(列)上的数字
        canSwipe: false, //标识是否可以滑动
        gridColumnCount: 0, //每行(列)方格数
        gameMode: 0, //游戏模式
        height: 80,
        width: 80
    },
    onInit() {
        //        this.initView(constants.MODE_CLASSIC);
    },
    onShow() {
    },
    initView(mode) {
        console.log("=== initView")
        this.gameMode = mode;
        this.canSwipe = true;
        //清空之前的数组数据
        this.cells = null;
        //初始化格子
        if (mode == constants.MODE_CLASSIC) {
            //经典模式
            this.gridColumnCount = Config.GRIDColumnCount;
        } else if (mode == constants.MODE_INFINITE) {
            // 无限模式
            this.gridColumnCount = 6;
        }
        if(this.gridColumnCount == 4) {
            this.height = 80;
            this.width = 80;
        } else if(this.gridColumnCount == 5) {
            this.height = 60;
            this.width = 60;
        } else if(this.gridColumnCount == 6) {
            this.height = 50;
            this.width = 50;
        }
        //初始化二维数组
        this.reset();
        this.startGame();
    },
    reset() {
        this.cells = new Array(this.gridColumnCount);
        for (var i = 0; i < this.gridColumnCount; i++) {
            var cellItem = new Array(this.gridColumnCount);
            for (var j = 0; j < cellItem.length; j++) {
                var cellEntity = new CellEntity();
                cellEntity.x = 0;
                cellEntity.y = 0;
                cellEntity.num = 0;
                cellEntity.showDisappearAnim = false;
                cellItem[j] = cellEntity;
            }
            this.cells[i] = cellItem;
        }
    },
//开始游戏
    async startGame() {
        this.reset();
        let fileName = Config.getTableName();
        var dataStr = await StorageNative.getTableData(fileName);
        console.log("=== getTableData: " + dataStr);
        var obj = JSON.parse(dataStr);
        if (obj.code == 0) {
            if (obj.result) {
                var data = JSON.parse(obj.result);
                console.log("=== data" + data);
                if (data && data.length > 2) {
                    this.resumeGame(data);
                } else {
                    this.initGame();
                }
            } else {
                this.initGame();
            }
        }
    },
//初始化游戏
    initGame() {
        this.addDigital(false);
        this.addDigital(false);
    },
//继续游戏
    resumeGame(data) {
        if (data == null || data.length == 0) {
            return;
        }
        for (var i = 0; i < data.length; i++) {
            var entity = data[i]; //CellEntity
            this.cells[entity.x][entity.y].x = entity.x;
            this.cells[entity.x][entity.y].y = entity.y;
            this.cells[entity.x][entity.y].num = entity.num;
            this.cells[entity.x][entity.y].showDisappearAnim = entity.showDisappearAnim;
            //设置格子出现动画
            this.setAppearAnim(this.cells[entity.x][entity.y]);
        }
    },
//重置游戏
    resetGame() {
        this.canSwipe = true;
        this.reset();
        // 随机添加两个数字（2或4）
        this.addDigital(false);
        this.addDigital(false);
    },
/**
     * 添加随机数字（2或4）或直接添加一个1024
     *
     * @param isCheat 是否是开挂
     */
    addDigital(isCheat) {
        this.getEmptyCell();
        if (this.emptyCellPoint.length > 0) {
            // 随机取出一个空格子的坐标位置
            var point = this.emptyCellPoint[parseInt(Math.random() * this.emptyCellPoint.length)];
            this.cells[point.x][point.y].x = point.x;
            this.cells[point.x][point.y].y = point.y;
            this.cells[point.x][point.y].showDisappearAnim = point.showDisappearAnim;
            if (isCheat) {
                this.cells[point.x][point.y].num = 1024;
            } else {
                this.cells[point.x][point.y].num = (Math.random() > 0.4 ? 2 : 4);
            }
            // 设置动画
            this.setAppearAnim(this.cells[point.x][point.y])
        }
    },
//获取空格子
    getEmptyCell() {
        this.emptyCellPoint.length = 0; // 清空
        // 遍历所有格子，记录所有空格子的坐标位置
        for (var i = 0; i < this.gridColumnCount; i++) {
            for (var j = 0; j < this.gridColumnCount; j++) {
                // 空格子
                if (this.cells[i][j].num <= 0) {
                    var point = new Point();
                    point.x = i;
                    point.y = j;
                    this.emptyCellPoint.push(point);
                }
            }
        }
    },
//获取当前游戏进度
    getCurrentProcess() {
        var data = [];
        for (var i = 0; i < this.gridColumnCount; i++) {
            for (var j = 0; j < this.gridColumnCount; j++) {
                var num = this.cells[i][j].num;
                if (num > 0) {
                    var entity = new CellEntity();
                    entity.x = i;
                    entity.y = j;
                    entity.num = num;
                    data.push(entity)
                }
            }
        }
        return data;
    },
    setAppearAnim(cellEntity) {
        //设置格子出现动画
        cellEntity.showDisappearAnim = true;
    },
//上滑
    swipeUp() {
        // 判断是否需要添加数字
        var needAddDigital = false;
        for (var i = 0; i < this.gridColumnCount; i++) {
            for (var j = 0; j < this.gridColumnCount; j++) {
                // 获取当前位置数字
                var currentDigital = this.cells[j][i].num;
                this.someData.push(currentDigital);
                if (currentDigital != 0) {
                    //记录数字
                    if (this.recordPreviousDigital == -1) {
                        this.recordPreviousDigital = currentDigital;
                    } else {
                        // 记录的之前的数字和当前数字不同
                        if (this.recordPreviousDigital != currentDigital) {
                            // 加入记录的数字
                            this.dataAfterSwipe.push(this.recordPreviousDigital);
                            this.recordPreviousDigital = currentDigital;
                        } else {
                            // 记录的之前的数字和当前的数字相同
                            // 加入*2
                            this.dataAfterSwipe.push(this.recordPreviousDigital * 2);
                            //记录得分
                            this.recordScore(this.recordPreviousDigital * 2);
                            // 重置记录数字
                            this.recordPreviousDigital = -1;
                        }
                    }
                }
            }
            if (this.recordPreviousDigital != -1) {
                this.dataAfterSwipe.push(this.recordPreviousDigital);
            }

            // 补0
            for (var p = this.dataAfterSwipe.length; p < this.gridColumnCount; p++) {
                this.dataAfterSwipe.push(0);
            }

            // 若原始数据和移动后的数据不同，视为界面发生改变
            if (!Tools.arrayEquals(this.someData, this.dataAfterSwipe)) {
                needAddDigital = true;
            }
            this.someData.length = 0;
            //重新设置格子数据
            for (var k = 0; k < this.dataAfterSwipe.length; k++) {
                this.cells[k][i].num = this.dataAfterSwipe[k]
            }
            // 重置数据
            this.recordPreviousDigital = -1;
            this.dataAfterSwipe.length = 0;
        }
        if (needAddDigital) {
            // 添加一个随机数字（2或4）
            this.addDigital(false);
            this.playSound();
        }
        this.judgeOverOrAccomplish();
    },
//下滑
    swipeDown() {
        // 判断是否需要添加数字
        var needAddDigital = false;
        for (var i = this.gridColumnCount - 1; i >= 0; i--) {
            for (var j = this.gridColumnCount - 1; j >= 0; j--) {
                // 获取当前位置数字
                var currentDigital = this.cells[j][i].num;
                this.someData.push(currentDigital);
                if (currentDigital != 0) {
                    //记录数字
                    if (this.recordPreviousDigital == -1) {
                        this.recordPreviousDigital = currentDigital;
                    } else {
                        // 记录的之前的数字和当前数字不同
                        if (this.recordPreviousDigital != currentDigital) {
                            // 加入记录的数字
                            this.dataAfterSwipe.push(this.recordPreviousDigital);
                            this.recordPreviousDigital = currentDigital;
                        } else { // 记录的之前的数字和当前的数字相同
                            this.dataAfterSwipe.push(this.recordPreviousDigital * 2);
                            //记录得分
                            this.recordScore(this.recordPreviousDigital * 2);
                            // 重置记录数字
                            this.recordPreviousDigital = -1;
                        }
                    }
                }
            }
            if (this.recordPreviousDigital != -1) {
                this.dataAfterSwipe.push(this.recordPreviousDigital);
            }

            // 补0
            var temp = this.gridColumnCount - this.dataAfterSwipe.length;
            for (var k = 0; k < temp; k++) {
                this.dataAfterSwipe.push(0);
            }

            this.dataAfterSwipe = this.dataAfterSwipe.reverse();
            this.someData = this.someData.reverse();

            // 若原始数据和移动后的数据不同，视为界面发生改变
            if (!Tools.arrayEquals(this.someData, this.dataAfterSwipe)) {
                needAddDigital = true;
            }
            this.someData.length = 0;
            //重新设置格子数据
            var index = 0;
            for (var p = 0; p < this.gridColumnCount; p++) {
                this.cells[p][i].num = this.dataAfterSwipe[index++]
            }
            // 重置数据
            this.recordPreviousDigital = -1;
            this.dataAfterSwipe.length = 0;
        }
        if (needAddDigital) {
            // 添加一个随机数字（2或4）
            this.addDigital(false);
            this.playSound();
        }
        this.judgeOverOrAccomplish();
    },
//左滑
    swipeLeft() {
        // 判断是否需要添加数字
        var needAddDigital = false;
        for (var i = 0; i < this.gridColumnCount; i++) {
            for (var j = 0; j < this.gridColumnCount; j++) {
                // 获取当前位置数字
                var currentDigital = this.cells[i][j].num;
                this.someData.push(currentDigital);
                if (currentDigital != 0) {
                    //记录数字
                    if (this.recordPreviousDigital == -1) {
                        this.recordPreviousDigital = currentDigital;
                    } else {
                        // 记录的之前的数字和当前数字不同
                        if (this.recordPreviousDigital != currentDigital) {
                            // 加入记录的数字
                            this.dataAfterSwipe.push(this.recordPreviousDigital);
                            this.recordPreviousDigital = currentDigital;
                        } else { // 记录的之前的数字和当前的数字相同
                            this.dataAfterSwipe.push(this.recordPreviousDigital * 2);
                            //记录得分
                            this.recordScore(this.recordPreviousDigital * 2);
                            // 重置记录数字
                            this.recordPreviousDigital = -1;
                        }
                    }
                }
            }
            if (this.recordPreviousDigital != -1) {
                this.dataAfterSwipe.push(this.recordPreviousDigital);
            }

            // 补0
            for (var p = this.dataAfterSwipe.length; p < this.gridColumnCount; p++) {
                this.dataAfterSwipe.push(0);
            }

            // 若原始数据和移动后的数据不同，视为界面发生改变
            if (!Tools.arrayEquals(this.someData, this.dataAfterSwipe)) {
                needAddDigital = true;
            }
            this.someData.length = 0;
            //重新设置格子数据
            for (var k = 0; k < this.dataAfterSwipe.length; k++) {
                this.cells[i][k].num = this.dataAfterSwipe[k]
            }
            // 每一行结束重置list
            this.dataAfterSwipe.length = 0;
            // 重置数据
            this.recordPreviousDigital = -1;
        }
        if (needAddDigital) {
            // 添加一个随机数字（2或4）
            this.addDigital(false);
            this.playSound();
        }
        this.judgeOverOrAccomplish();
    },
//右滑
    swipeRight() {
        // 判断是否需要添加数字
        var needAddDigital = false;
        for (var i = this.gridColumnCount - 1; i >= 0; i--) {
            for (var j = this.gridColumnCount - 1; j >= 0; j--) {
                // 获取当前位置数字
                var currentDigital = this.cells[i][j].num;
                this.someData.push(currentDigital);
                if (currentDigital != 0) {
                    //记录数字
                    if (this.recordPreviousDigital == -1) {
                        this.recordPreviousDigital = currentDigital;
                    } else {
                        // 记录的之前的数字和当前数字不同
                        if (this.recordPreviousDigital != currentDigital) {
                            // 加入记录的数字
                            this.dataAfterSwipe.push(this.recordPreviousDigital);
                            this.recordPreviousDigital = currentDigital;
                        } else { // 记录的之前的数字和当前的数字相同
                            this.dataAfterSwipe.push(this.recordPreviousDigital * 2);
                            //记录得分
                            this.recordScore(this.recordPreviousDigital * 2);
                            // 重置记录数字
                            this.recordPreviousDigital = -1;
                        }
                    }
                }
            }
            if (this.recordPreviousDigital != -1) {
                this.dataAfterSwipe.push(this.recordPreviousDigital);
            }

            // 补0
            var temp = this.gridColumnCount - this.dataAfterSwipe.length;
            for (var k = 0; k < temp; k++) {
                this.dataAfterSwipe.push(0);
            }

            this.dataAfterSwipe = this.dataAfterSwipe.reverse();
            this.someData = this.someData.reverse();

            // 若原始数据和移动后的数据不同，视为界面发生改变
            if (!Tools.arrayEquals(this.someData, this.dataAfterSwipe)) {
                needAddDigital = true;
            }
            this.someData.length = 0;
            //重新设置格子数据
            var index = 0;
            for (var p = 0; p < this.gridColumnCount; p++) {
                this.cells[i][p].num = this.dataAfterSwipe[index++]
            }
            // 重置数据
            this.recordPreviousDigital = -1;
            this.dataAfterSwipe.length = 0;
        }
        if (needAddDigital) {
            // 添加一个随机数字（2或4）
            this.addDigital(false);
            this.playSound();
        }
        this.judgeOverOrAccomplish();

    },
//记录得分
    recordScore(score) {
        // 获取分数
        console.log("===recordScore:" + score);
        this.$emit("updateScore", score);
    },
//检查游戏是否结束或达成游戏目标
    judgeOverOrAccomplish() {
        // 判断游戏结束的标识
        var isOver = true;
        // 判断游戏是否结束
        // 格子都不为空且相邻的格子数字不同
        over:
        for (var i = 0; i < this.gridColumnCount; i++) {
            for (var j = 0; j < this.gridColumnCount; j++) {
                // 有空格子，游戏还可以继续
                if (this.cells[i][j].num == 0) {
                    isOver = false;
                    break over;
                }
                // 判断左右上下有没有相同的
                if (j < this.gridColumnCount - 1) {
                    if (this.cells[i][j].num == this.cells[i][j + 1].num) {
                        isOver = false;
                        break over;
                    }
                }
                if (i < this.gridColumnCount - 1) {
                    if (this.cells[i][j].num == this.cells[i + 1][j].num) {
                        isOver = false;
                        break over;
                    }
                }
            }
        }

        if (isOver) {
            this.canSwipe = false;
            this.sendGameOverMsg("ACTION_LOSE")
        }
        // 经典模式下才判赢
        if (this.gameMode == 0) {
            // 判断是否达成游戏目标
            for (var i = 0; i < this.gridColumnCount; i++) {
                for (var j = 0; j < this.gridColumnCount; j++) {
                    // 有一个格子数字到达2048则视为达成目标
                    if (this.cells[i][j].num >= 2048) {
                        this.canSwipe = false;
                        console.log("===goalTime: " + Config.GetGoalTime);
                        let currentTime = Config.GetGoalTime + 1;
                        StorageNative.putGoalTime(currentTime);
                        Config.GetGoalTime = currentTime;
                        this.sendGameOverMsg("ACTION_WIN");
                    }
                }
            }
        }
    },
    playSound() {
        if (Config.VolumeState) {
            SoundNative.playSound(1);
        }
    },
//发送游戏结束消息
    sendGameOverMsg(action) {
        this.$emit("gameOver", action);
    },
//处理滑动事件
    handleTouchStart(info) {
        var touch = info.touches[0];
        this.setX = touch.globalX;
        this.setY = touch.globalY;
    },
    handleTouchEnd(info) {
        if (!this.canSwipe) {
            return;
        }
        var changedTouches = info.changedTouches[0];
        this.offsetX = changedTouches.globalX - this.setX;
        this.offsetY = changedTouches.globalY - this.setY;
        var orientation = this.getOrientation(this.offsetX, this.offsetY);
        if (orientation == 0) {
            this.swipeRight();
        } else if (orientation == 1) {
            this.swipeLeft();
        } else if (orientation == 2) {
            this.swipeDown();
        } else if (orientation == 3) {
            this.swipeUp();
        }

    },
/**
     * 获取滑动方向<br />
     * 注：先依据在轴上滑动距离的大小，判断在哪个轴上滑动
     *
     * @param offsetX 在X轴上的移动距离
     * @param offsetY 在Y轴上的移动距离
     * @return 滑动方向
     * <br />
     * 注：0右滑、1左滑、2下滑、3上滑、-1未构成滑动
     */
    getOrientation(offsetX, offsetY) {
        if (Math.abs(offsetX) > Math.abs(offsetY)) {
            if (offsetX > this.MIN_DIS) {
                return 0;
            } else if (offsetX < -this.MIN_DIS) {
                return 1;
            } else {
                return -1;
            }
        } else { // Y轴移动
            if (offsetY > this.MIN_DIS) {
                return 2;
            } else if (offsetY < -this.MIN_DIS) {
                return 3;
            } else {
                return -1;
            }
        }
    },
    getBackgroundColor(number) {
        switch (number) {
            case 0:
            return "#50549A";
            case 2:
            return "#41C9B8";
            case 4:
            return "#00B2A1";
            case 8:
            return "#ED5471";
            case 16:
            return "#C23361";
            case 32:
            return "#B81C64";
            case 64:
            return "#9E005D";
            case 128:
            return "#FFB33C";
            case 256:
            return "#F68530";
            case 512:
            return "#E85938";
            case 1024:
            return "#3C1F68";
            case 2048:
            return "#FF4081";
            default:
                return "#515BD4";
        }
    }
}

/**
 *
 */
function Point() {
    var x = 0;
    var y = 0;
}

function CellEntity() {
    var x = 0; //x轴位置
    var y = 0; //y轴位置
    var num = 0; //数字
    var showDisappearAnim = false;
}
